package vn.gq.tym.utils;

import java.util.Random;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.AdView;

public class AdmobAdsHandler implements AdListener {
	
	public static final int DELAY_TIME_FAILED;
	public static final int DELAY_TIME_RELOAD;
	
	private AdView adView;
	private Random mRandom = new Random();
	
	static {
		DELAY_TIME_FAILED = 30000;
		DELAY_TIME_RELOAD = 60000;
	}
	
	public AdmobAdsHandler(AdView adView) {
		adView.setAdListener(this);
		this.adView = adView;
	}
	
	public void loadAds() {
		if (adView != null) adView.post(loadAdsRun);
	}
	
	public void onStop() {
		if (adView != null) adView.stopLoading();
	}
	
	public void onDestroy() {
		if (adView != null) adView.destroy();
	}
	
	public Runnable loadAdsRun = new Runnable() {
		
		@Override
		public void run() {
			if (adView != null) {
				adView.loadAd(new AdRequest());
			}
		}
	};

	@Override
	public void onDismissScreen(Ad ad) {
	}


	@Override
	public void onFailedToReceiveAd(Ad ad, ErrorCode e) {
		adView.stopLoading();
		adView.removeCallbacks(loadAdsRun);
		adView.postDelayed(loadAdsRun, DELAY_TIME_FAILED);
	}

	@Override
	public void onLeaveApplication(Ad ad) {
	}


	@Override
	public void onPresentScreen(Ad ad) {
	}

	@Override
	public void onReceiveAd(Ad ad) {
		ScaleAnimation zoomIn = new ScaleAnimation(0.5f, 1f, 0.5f, 1f, 
				Animation.RELATIVE_TO_SELF, .5f, Animation.RELATIVE_TO_SELF, .5f);
		zoomIn.setDuration(500);
		float distance = adView.getHeight();
		TranslateAnimation slideDown = new TranslateAnimation(0, 0, -distance, 0);
		slideDown.setDuration(500);
		int idx = mRandom.nextInt(2);
		if (idx == 0)
			adView.startAnimation(zoomIn);
		else
			adView.startAnimation(slideDown);
		adView.stopLoading();
		adView.removeCallbacks(loadAdsRun);
		adView.postDelayed(loadAdsRun, DELAY_TIME_RELOAD);
	}
}
